import axios from 'axios'
import store from '@/store'
import {message} from 'ant-design-vue'
// import qs from 'qs'

const service = axios.create({
  baseURL:'/baiduapi',
  timeout:1000000
})

axios.defaults.withCredentials = true// 携带cookie

service.interceptors.request.use(
  async config=>{
    if(config.method == 'post'){
      // config.data = qs.stringify(config.data);
      config.headers['Content-Type'] = 'application/json'
    }
    if(store.state.user.userInfo){
      config.headers['Authori-zation'] = '' + store.state.user.userInfo.token;
    }
    if(store.state.dianpu.id){
      config.headers['Store-id'] = '' + store.state.dianpu.id;
    }else{ //页面强刷后会导致store消失，调用getId方法
      await store.dispatch('dianpu/getId')
      config.headers['Store-id'] = '' + store.state.dianpu.id
    }
    config.headers['Access-Control-Allow-Origin'] = '*'
    return config
  },
  error=>{
    return error
  }
)

service.interceptors.response.use(
  response=>{
    // console.log('response', response)
    return new Promise((resolve,reject) => {
      let errcode = response.data?response.data.errcode:0
      let errmsg = response.data?response.data.errmsg:''
      switch(errcode){
        case 0:
        case "0":
        case "1000":
        case "200":
          resolve(response.data)
          break;
        case "40001":
          if(errmsg=='未登录'){
            store.state.user.showUnlogin?message.error(errmsg):''
            store.commit('user/setShowUnlogin',false)
            setTimeout(() => {
              window.location.href = '/bd/#/login'
            }, 800);
            reject(response.data)
          }else{
            message.error(errmsg)
            reject(response.data)
          }
          break;
        case "40009":
          store.state.user.showUnlogin?message.error(errmsg):''
          store.commit('user/setShowUnlogin',false)
          setTimeout(() => {
            window.location.href = '/bd/#/login'
          }, 800);
          reject(response.data)
          break;
        default:
          message.error(errmsg)
          reject(response.data)
          break;
      }
    })
  },
  error=>{
    console.log(error)
    message.error('请求失败')
    return new Promise((resolve,reject) => {
      reject(error)
    })
  }
)

export default service